<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com>
// +----------------------------------------------------------------------

namespace Admin\Model;
use Think\Model;
/**
 * 询盘模型
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */

class InquiryModel extends Model {
    protected $_validate = array(
        array('title', 'require', '询盘标题不能为空', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
        //array('title', '', '询盘产品已经存在', self::VALUE_VALIDATE, 'unique', self::MODEL_BOTH),
        array('remark', 'require', '备注不能为空', self::EXISTS_VALIDATE , 'regex', self::MODEL_BOTH),
    );

    protected $_auto = array(
        array('creater', 'is_login', self::MODEL_INSERT, 'function'),
        array('user_id', 'is_login', self::MODEL_UPDATE, 'function'),
        array('title', 'trim', self::MODEL_INSERT, 'function'),
        array('mano', 'genMano', self::MODEL_INSERT, 'callback'),
        array('create_time', NOW_TIME, self::MODEL_INSERT),
        array('update_time', NOW_TIME, self::MODEL_BOTH),
        //array('status', '1', self::MODEL_BOTH),
    );

    /**
     * 获取配置列表 TODO
     * @return array 配置数组
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function lists(){
        $map    = array('status' => 1);
        $data   = $this->where($map)->field('type,name,value')->select();
        
        $config = array();
        if($data && is_array($data)){
            foreach ($data as $value) {
                $config[$value['name']] = $this->parse($value['type'], $value['value']);
            }
        }
        return $config;
    }

    
        /**注意type首字母大写
     *生成单号如 RK20110528-001 ，前几位为当前单子的日期，后三位自动增长
     */
    public function genMano($type='Inquiry'){
        $currday = date('Ymd');
        $prefix = '';

        switch ($type){
            case 'Buy'://采购计划
                $prefix = 'CG';
                break;
            case 'Inquiry'://入库
            default:
                $prefix = 'XD';
        }

        $model = M($type);
            $lastNo = $model ->where('mano like \'%'.$currday.'%\'')->order('id desc')->field('mano')->find();
            $value = explode('-',$lastNo['mano'] );


        if (empty($value)) {
            return $no = $prefix . $currday . '-001';
        } else {
            if (substr($value['0'], 2) == $currday) {
                $value['1'] += 1;
                $value['1'] = sprintf("%03d", $value['1']); //格式化为001
            } else {
                $value['1'] = '001';
            }
            return $no = $prefix . $currday . '-' . $value['1'];
        }
    }

}
